package com.sgffsg.learn.javalib.interview;

/**
 * @author: lmk
 * @date: 2024/4/25
 * @desc:
 */
public class MyList<T> {

    Object[] items;
    int currentIndex;

    public MyList() {
        items = new Object[16];
    }

    public void add(T item) {
        items[currentIndex++] = item;
        if (currentIndex >= items.length){
            resize();
        }
    }

    private void resize(){
        Object[] temp = new Object[items.length * 2];
        for (int i = 0; i < items.length;i++){
            temp[i] = items[i];
        }
        items = temp;
    }

    public T get(int index) {
        if (index > currentIndex){
            throw new IllegalArgumentException("Index out of range");
        } else {
            return (T) items[index];
        }
    }

    public void remove(int index) {
        if (index > currentIndex) {
            throw new IllegalArgumentException("Index out of range");
        } else {
            if (index == items.length - 1) {
                items[index] = null;
            } else {
                for (int i = index; i <= currentIndex; i++) {
                    items[i] = items[i + 1];
                }
            }
            currentIndex--;
        }
    }

    public void clear() {
        for (int i = 0; i <= currentIndex; i++) {
            items[i] = null;
        }
    }
}
